<%@page import="java.util.*"%>
<%@page import="iBoxDB.LocalServer.Box"%>
<%@page import="java.io.File"%>
<%@page import="mydb.MyDB"%>
<%@page import="java.util.concurrent.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8" session="false" %>

<%
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
%>


<%    synchronized (MyDB.testLock) {
        MyDB.create(this.getServletContext().getRealPath("/WEB-INF") + File.separatorChar
                + "DB" + File.separatorChar);

        Box box = MyDB.instance.cube();
        try {
            long rs = box.selectCount("from test");
            if (rs == 0) {
                for (long i = 1; i <= 10000; i++) {
                    final Long id = i;
                    HashMap<String, Object> map = new HashMap<String, Object>() {
                        {
                            put("id", id);
                            put("value", id * 2L);
                            put("msg", id + "既方既皂，既坚既好，不稂不莠。去其螟螣，及其蟊贼，无害我田稚. --螟螣and蟊贼 2 types of bug");
                        }
                    };
                    box.bind("test").insert(map);
                }
            }
            box.commit();
        } finally {
            box.close();
        }

        Box[] cs = new Box[10];
        ExecutorService es = Executors.newFixedThreadPool(cs.length);
        Future<Long>[] fs = new Future[cs.length];
        for (int i = 0; i < cs.length; i++) {
            cs[i] = MyDB.instance.cube();
        }
        try {
            long begin = System.currentTimeMillis();
            for (int i = 0; i < cs.length; i++) {
                final Box c = cs[i];
                fs[i] = es.submit(
                        new Callable<Long>() {
                            public Long call() throws Exception {
                                long l = 0;
                                for (Map<String, Object> map : c.select("from test")) {
                                    if (map.get("msg").toString().startsWith(
                                            map.get("id").toString()
                                    )) {
                                        l += (Long) map.get("value");
                                    }
                                }
                                return l;
                            }
                        }
                );
            }
            long count = 0;
            for (int i = 0; i < cs.length; i++) {
                count += fs[i].get();
            }
            out.println(System.currentTimeMillis() - begin + "," + count);
        } finally {
            for (int i = 0; i < cs.length; i++) {
                cs[i].close();
            }
        }
        es.shutdown();
        es = null;
        System.gc();
    }

%>
